#!/bin/bash


TARGET_FILE=main

if [ $# -gt 0 ]; then
    if [[ $1 == "clean" ]]; then
        cmake --build build -t clean
        exit $?
    fi

    if [[ $1 == "dclean" ]]; then
        rm build output -rf
        exit $?
    fi

    GDB_DEBUG=
    if [[ $1 == "gdb" ]]; then
        GDB_DEBUG="-s -S"
    fi

    if [[ $1 == "qemu" || $1 == "gdb" ]]; then #-nographic -monitor pty
        qemu-system-arm  -M stm32vldiscovery ${GDB_DEBUG} -nographic -kernel output/${TARGET_FILE}.bin
        exit $?
    fi


fi

if [ ! -e build ]; then
    cmake -DCMAKE_TOOLCHAIN_FILE=cmake/arm-toolchain.cmake -B build -S . 
    if [ $? -ne 0 ]; then
        exit $?
    fi

    if [[ ! -e "output" ]]; then
        mkdir output/
    fi
fi

cmake --build build -t all
if [ $? -eq 0 ]; then
    cp build/${TARGET_FILE}.elf output/ -rf
    cp build/${TARGET_FILE}.elf.bin output/${TARGET_FILE}.bin 
    cp build/${TARGET_FILE}.elf.map output/${TARGET_FILE}.map 
    cp build/${TARGET_FILE}.elf.s output/${TARGET_FILE}.s 
fi
